package me.flyray.netty.handlers;

import java.net.InetAddress;

import com.github.wxiaoqi.security.cache.CacheProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;

@Component
@Qualifier("serverHandler")
@Sharable
public class ServerHandler extends SimpleChannelInboundHandler<String> {

	private static final Logger log = LoggerFactory.getLogger(ServerHandler.class);
	
	@Override
	//public void messageReceived(ChannelHandlerContext ctx, String msg)
	public void channelRead0(ChannelHandlerContext ctx, String msg)
			throws Exception {
		log.info("client msg:"+msg);
//		String clientIdToLong= ctx.channel().id().asLongText();
//		log.info("client long id:"+clientIdToLong);
//		String clientIdToShort= ctx.channel().id().asShortText();
//		log.info("client short id:"+clientIdToShort);
		//拿到消息之后要解析消息
		// 将收到app建立连接或生成二维码后发送的消息解析 msg =  消息类型|收款类型|收款账号|订单号|图片base64
		//如果消息类型是00 则是建立连接时的消息 后面为空 eg msg = 00||||
		//如果消息类型为01 则是生成二维码的消息
		//如果消息类型为00 将连接设备保存到NettyChannelMap中，key=收款账号 value=channel 方便在getReceivablesQr中get
		
		if("Heartbeat".equals(msg)){
			//忽略心跳请求
			return;
		}
		
		String[] words = msg.split("\\|");
		String msgType = words[0];
		String number = words[2];
		
		if ("00".equals(msgType)) {
			NettyChannelMap.add(number,(SocketChannel)ctx.channel());
		}else if ("01".equals(msgType)){
			// 如果消息类型为生成二维码，则讲二维码数据写入redis中，key为订单号，等等消费 方便在getReceivablesQr中get
			String orderId = words[3];
			String qr = words[4];
			CacheProvider.set(orderId,qr);
		}

		//成功之后返回一个消息
		ctx.channel().writeAndFlush("ok");
			

	}
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		log.info("RamoteAddress : " + ctx.channel().remoteAddress() + " active !");
		String clientIdToLong= ctx.channel().id().asLongText();
		log.info("client long id:"+clientIdToLong);
		String clientIdToShort= ctx.channel().id().asShortText();
		log.info("client short id:"+clientIdToShort);
		NettyChannelMap.add("w-lock",(SocketChannel)ctx.channel());
		NettyChannelMap.add(clientIdToLong,(SocketChannel)ctx.channel());
		NettyChannelMap.get(clientIdToLong);
        ctx.channel().writeAndFlush( "Welcome to " + InetAddress.getLocalHost().getHostName() + " service!\n");
        
		super.channelActive(ctx);
	}
	

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		log.info("\nChannel is disconnected");
		// channel失效，从Map中移除
		//SocketChannel socketChannel = (SocketChannel) ctx.channel();
		NettyChannelMap.remove((SocketChannel)ctx.channel());
		super.channelInactive(ctx);
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		System.out.println("ServerHandler.channelReadComplete()");
		ctx.flush();
	}
}